
package com.wangge.forkJoin;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RecursiveTask;

public class Calculator extends RecursiveTask<Long> {

  private static final long serialVersionUID = 8063259450662743843L;

  private Long start;
  private Long end;
  private final Long Sspilt = 100L;

  @Override
  protected Long compute() {
    Long sum = 0L;
    if ((start - end) < Sspilt) {
      for (Long i = start; i < end; i++) {
        sum += i;
      }
    } else {
      Long middle = (start + end) / 2;
      Calculator left = new Calculator(start, middle);
      Calculator right = new Calculator(middle + 1, end);
      left.fork();
      right.fork();
      sum = left.join() + right.join();
    }
    return sum;
  }

  public Calculator(Long start, Long end) {
    this.start = start;
    this.end = end;
  }

  public volatile int i = 0;

  public static void main(String[] args) {
    ExecutorService ex = Executors.newCachedThreadPool();
    Calculator c = new Calculator(0L, 20L);
    Waiter w = new Waiter(c);
    ex.execute(w);
    try {
      Thread.sleep(1000);
      c.i = 1;
      Thread.sleep(1000);
      c.i = 1;
      Thread.sleep(1000);
      c.i = 1;
      Thread.sleep(1000);
      c.i = 1;
      ex.shutdownNow();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}
